// Package logicGen
// @Author Spume
// @Date 2024-12-31 10:49

package main

import (
	"context"
	"fmt"
	"os"
	"path"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/text/gstr"
)

type cMain struct {
	g.Meta `name:"main"`
}

type cMainHttpInput struct {
	g.Meta    `name:"gen" brief:"gen logic code"`
	DaoName   string `v:"required" name:"daoName" short:"d"  brief:"-d daoName"`
	LogicName string ` short:"l" name:"logicName"  brief:"-l logicName"`
	Table     bool   `short:"t" name:"table" orphan:"true"  brief:"-t table use g.DB()"`
	TableName string `short:"tb" name:"tableName"   brief:"-tb tableName"`
}
type cMainHttpOutput struct{}

func (c *cMain) Gen(ctx context.Context, in cMainHttpInput) (out *cMainHttpOutput, err error) {

	v := g.View()

	err = v.SetPath("../../manifest/template")
	if err != nil {
		return
	}
	if in.LogicName == "" {
		in.LogicName = in.DaoName
	}
	tableName := in.TableName
	if tableName == "" {
		tableName = gstr.CaseSnake(in.DaoName)
	}

	tplName := "tplLogic.tpl"
	if in.Table {
		tplName = "tplLogic2.tpl"
	}

	reslut, err := v.Parse(ctx, tplName, g.Map{
		"TplTableNameCamelCase": in.DaoName,
		"TplLogicName":          in.LogicName,
		"TableName":             tableName,
	})
	if err != nil {
		return
	}

	logicName := gstr.CaseSnake(in.LogicName)
	pathFile := path.Join(gfile.Pwd(), "internal", "logic", logicName, logicName+".go")

	// Write file content to disk.
	if gfile.Exists(pathFile) {
		fmt.Printf("%s exists", pathFile)
	} else {
		var tplFile *os.File
		tplFile, err = gfile.Create(pathFile)
		if err != nil {
			return
		}
		defer tplFile.Close()
		_, err = tplFile.WriteString(reslut)
		if err != nil {
			return
		}
	}

	return
}

func main() {
	cmd, err := gcmd.NewFromObject(cMain{})
	if err != nil {
		panic(err)
	}
	cmd.Run(gctx.New())
}

type sTest struct {
}

func (s *sTest) Create(ctx context.Context, in *interface{}) (insId int64, err error) {
	return g.DB().Model("").Ctx(ctx).Data(in).InsertAndGetId()
}
